package com.imooc.reader.controller.management;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.reader.exception.BussiException;
import com.imooc.reader.entity.Book;
import com.imooc.reader.service.BookService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/management/book")
public class MBookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/index.html")
    public ModelAndView showBook(){
        return new ModelAndView("/management/book");
    }

    /**
     * wangEditor文件上传
     * @param file 上传文件
     * @param request 原生请求对象
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("img") MultipartFile file , HttpServletRequest request) throws IOException {
        //得到上传目录
        String path=request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path);
        //文件名
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        //扩展名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File desFile=new File(path +"/"+fileName + suffix);
        if(!desFile.getParentFile().exists()){
            desFile.mkdirs();
        }
        //保存文件到upload目录
        file.transferTo(desFile);

        Map result = new HashMap();
        result.put("errno", 0);
        result.put("data", new String[]{"/upload/" + fileName + suffix});
        return result;
    }


    @RequestMapping("/create")
    @ResponseBody
    public Map createBook(Book book){
        Map map=new HashMap();
        try{
            book.setEvaluationQuantity(0);
            book.setEvaluationScore(0f);

            //解析图书详情
            Document doc = Jsoup.parse(book.getDescription());
            //获取图书详情中第一图的img标签内容
            Element img = doc.select("img").first();
            //获取img标签中的src属性
            String cover = img.attr("src");
            book.setCover(cover);

            bookService.createBook(book);

            map.put("code","0");
            map.put("msg","success");
        }catch (BussiException ex){
            ex.printStackTrace();
            map.put("code",ex.getCode());
            map.put("msg",ex.getMsg());
        }
        return map;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map list(Integer page,Integer limit){

        Map map=new HashMap();
        IPage<Book> paging = bookService.paging(null, null, page, limit);
        map.put("code","0");
        map.put("msg","success");
        map.put("count",paging.getTotal());
        map.put("data",paging.getRecords());

        return map;
    }

    @RequestMapping("/delete/{bookId}")
    @ResponseBody
    public Map deleteBook(@PathVariable("bookId") Long bookId){

        Map map=new HashMap();
        try{
            bookService.deleteBook(bookId);
            map.put("code","0");
            map.put("msg","success");
        }catch (BussiException ex){
            map.put("count",ex.getCode());
            map.put("data",ex.getMsg());
        }

        return map;
    }

    @RequestMapping("/id/{bookId}")
    @ResponseBody
    //更新回填
    public Map selectBook(@PathVariable("bookId") Long bookId){
        Map map=new HashMap();
        try{
            Book bookById = bookService.findBookById(bookId);
            map.put("code","0");
            map.put("msg","success");
            map.put("data",bookById);
        }catch (BussiException ex){
            map.put("count",ex.getCode());
            map.put("data",ex.getMsg());
        }
        return map;
    }
    @RequestMapping("/update")
    @ResponseBody
    public Map updateBook(Book book){
        Map map=new HashMap();
        try{
            Book rawBook = bookService.findBookById(book.getBookId());
            rawBook.setBookName(book.getBookName());
            rawBook.setAuthor(book.getAuthor());
            rawBook.setCategoryId(book.getCategoryId());
            rawBook.setDescription(book.getDescription());
            rawBook.setSubTitle(book.getSubTitle());

            //解析图书详情
            Document doc = Jsoup.parse(book.getDescription());
            //获取图书详情中第一图的img标签内容
            Element img = doc.select("img").first();
            //获取img标签中的src属性
            String cover = img.attr("src");

            rawBook.setCover(cover);

            bookService.updateBook(rawBook);

            map.put("code","0");
            map.put("msg","success");
        }catch (BussiException ex){
            ex.printStackTrace();
            map.put("count",ex.getCode());
            map.put("data",ex.getMsg());
        }
        return map;
    }

}
